package com.deuwise.common.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;

/**
 * Copyright
 *
 * @author chenwenchao
 * @date 2018/11/15 0015
 * Description:文件操作帮助类
 */
public class FileHelperUtils {

    private static final int  BUFFER_SIZE = 2 * 1024;
    /**
     * 错误输入日志
     */
    public static final Logger log = LoggerFactory.getLogger(FileHelperUtils.class);
    /**

     * 压缩成ZIP 方法2
     * @param srcFiles 需要压缩的文件列表
     * @param out           压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 清理目录中过期的文件
     *
     * @param dirPath
     *            ：目录路径
     * @return
     */
    @SuppressWarnings("unchecked")
    public static boolean deleteFiles(String dirPath, int days) {

        // 计算备份日期，备份该日期之前的文件
        Date pointDate = new Date();
        pointDate=DateUtils.endOfDay(pointDate);
        if(days<=0){
            days=1;
        }
        long timeInterval = pointDate.getTime() - convertDaysToMilliseconds(days);
        pointDate.setTime(timeInterval);


        // 设置文件过滤条件
        IOFileFilter timeFileFilter = FileFilterUtils.ageFileFilter(pointDate, true);
        IOFileFilter fileFiles = FileFilterUtils.and(FileFileFilter.FILE, timeFileFilter);

        // 删除符合条件的文件
        File deleteRootFolder = new File(dirPath);
        Iterator itFile = FileUtils.iterateFiles(deleteRootFolder, fileFiles, TrueFileFilter.INSTANCE);
        while (itFile.hasNext()) {
            File file = (File) itFile.next();
            boolean result = file.delete();
            if (!result) {
                log.error("Failed to delete file of :" + file);
                return false;
            }
        }

        // 清理空的文件夹
        File[] forderList = deleteRootFolder.listFiles();
        if (forderList != null && forderList.length > 0) {
            for (int i = 0; i < forderList.length; i++) {
                deleteEmptyDir(forderList[i]);
            }
        }

        return true;
    }
    /**
     * 天与毫秒的转换
     *
     * @param days
     * @return
     */
    private static long convertDaysToMilliseconds(int days) {
        return days * 24L * 3600 * 1000;
    }
    /**
     * 循环删除空的文件夹
     *
     * @param dir
     */
    private static void deleteEmptyDir(File dir) {
        if (dir.isDirectory()) {
            File[] fs = dir.listFiles();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    File tmpFile = fs[i];
                    if (tmpFile.isDirectory()) {
                        deleteEmptyDir(tmpFile);
                    }
                    if (tmpFile.isDirectory() && tmpFile.listFiles().length <= 0) {
                        tmpFile.delete();
                    }
                }
            }
            if (dir.isDirectory() && dir.listFiles().length == 0) {
                dir.delete();
            }
        }
    }

    /**
     * 获取日志备份路径
     * @return
     */
    public static String getLogSavePath(){
        ClassPathResource resource = new ClassPathResource("logback-spring.xml");
        InputStream inputStream = null;
        try {
            inputStream = resource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建一个SAXReader对象
        SAXReader sax = new SAXReader();
        String logPath="";
        try {

            //获取document对象,如果文档无节点，则会抛出Exception提前结束
            Document document = sax.read(inputStream);
            //获取根节点
            Element root = document.getRootElement();
            List<Element> properyList =  root.elements("property");
            for (Element element : properyList) {
                List<Attribute> attributes=element.attributes();
                if(attributes.get(0).getValue().equals("log_dir")){
                    logPath=attributes.get(1).getStringValue();
                    System.out.println(logPath);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  logPath;
    }
}
